package uf.audit.db.support;

import uf.audit.util.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 线程池的配置
 */
public class ThreadPoolPlugin {
    /**
     * 核心线程数量
     */
    private static int corePoolsize;

    /**
     * 线程池最大容纳线程数
     */
    private static int maxmunPoolSize;

    /**
     * 线程空闲后的存活时长
     */
    private static int keepAliveTime;

    private static String filepath = new String("/config.properties");

    public ThreadPoolPlugin(Properties properties) {
        Properties ps = properties;
        initThreadPool(toInt(ps.getProperty("INIT_THREAD_SIZE", "1")),
                toInt(ps.getProperty("MAX_POOL_SIZE", "1")),
                toInt(ps.getProperty("KEEP_ALIVE_TIME", "1")));
    }

    private int toInt(String str) {
        if (str != null && !"".equals(str))
            return Integer.parseInt(str);
        return 1;
    }

    public void initThreadPool(int corePoolsize, int maxmunPoolSize, int keepAliveTime) {
        this.corePoolsize = corePoolsize;
        this.keepAliveTime = keepAliveTime;
        this.maxmunPoolSize = maxmunPoolSize;
    }


    public static ThreadPoolPlugin buildFromProperties(String filepath) throws Exception {
        Properties properties = Utils.getProperties(filepath);
        return new ThreadPoolPlugin(properties);
    }

    public ThreadPoolPlugin(File propertyfile) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(propertyfile);
            Properties ps = new Properties();
            ps.load(fis);
            initThreadPool(toInt(ps.getProperty("INIT_THREAD_SIZE", "1")),
                    toInt(ps.getProperty("MAX_POOL_SIZE", "1")),
                    toInt(ps.getProperty("KEEP_ALIVE_TIME", "1")));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    public ThreadPoolPlugin() {
        try {
            ThreadPoolPlugin threadPoolPlugin = (ThreadPoolPlugin) buildFromProperties(filepath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getCoreThread() {
        return this.corePoolsize;
    }
}
